﻿using System.IO;
using System.Text.RegularExpressions;

namespace Transliterator
{
    public class PoFileProcesor
    {
        public PoFileProcesor(ITransliterator transliterator, string path)
        {
            PoFile = new FileInfo(path);
            Transliterator = transliterator;
        }

        private FileInfo PoFile { get; set; }
        private ITransliterator Transliterator { get; set; }

        public void Transliterate()
        {
            string outputPath = PoFile.FullName.Replace("sr-Latn-RS", "sr-Cyrl-RS");
            string outputDir = PoFile.DirectoryName.Replace("sr-Latn-RS", "sr-Cyrl-RS");

            CreateOutputDirectoryIfItDoesNotExist(outputDir);

            using (var fs = new FileStream(outputPath, FileMode.Create, FileAccess.Write, FileShare.Write))
            {
                using (var writer = new StreamWriter(fs))
                {
                    using (StreamReader reader = PoFile.OpenText())
                    {
                        while (reader.Peek() >= 0)
                        {
                            string line = reader.ReadLine();

                            if (line != null)
                            {
                                var regex = new Regex("msgstr \"(.*)\"", RegexOptions.Singleline);

                                if (regex.Match(line).Success)
                                    line = string.Format("msgstr \"{0}\"", Transliterator.TransliterujUCirilicu(regex.Match(line).Groups[1].Value));

                                writer.WriteLine(line);
                            }
                        }
                    }
                }
            }
        }

        private void CreateOutputDirectoryIfItDoesNotExist(string outputPath)
        {
            if (!Directory.Exists(outputPath))
                Directory.CreateDirectory(outputPath);
        }
    }
}